﻿using System;
using System.Collections.Generic;

using System.Text;
using CsharpHttpHelper;
using CsharpHttpHelper.Enum;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Net;

using System.Windows.Forms;
using System.Xml;
namespace AutoSend
{
    public class myhttp
    {
        public static string cookie;
        public static HttpHelper http = new HttpHelper();
        public static string strjs;
        public static string mainurl;
        public static string myid;
        public static string sgid;
        public static string uploadset;
        public static string islogin = "NO";
        public static CookieCollection cccookie;
        public static int getconeid( out int twoid)
        {
            int i = 0;
            twoid=-1;
            string httppub = "http://b2b.sg560.com/member/sell/SellTosr" + myhttp.sgid + ".html";
            HttpResult r = HttpGet(httppub, "");
            string hidtitlc = myhttp.GetHtmlID(r.Html.ToString(), "input", "coneid");
            string hidtitlc2 = myhttp.GetHtmlID(r.Html.ToString(), "input", "ctwoid");
            int.TryParse(hidtitlc, out i);
            if(hidtitlc2!="")
                int.TryParse(hidtitlc2, out twoid);
            return i;
        }
        public static bool DownloadFile(string URL, string filename)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                myrp.Close();
                Myrq.Abort();
                return true;
            }
            catch (System.Exception e)
            {                
                return false;
            }
        }
        public static List<CsharpHttpHelper.Item.ImgItem> GetImags(string url)
        {
            HttpHelper http = new HttpHelper();
            //创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "get",//URL     可选项 默认为Get   
                ContentType = "text/html",//返回类型    可选项有默认值   
                Cookie = cookie,
                //ContentType = "application/x-www-form-urlencoded",//返回类型    可选项有默认值   
            };
            //请求的返回值对象
            HttpResult result = http.GetHtml(item);
            //获取请请求的Html
            string html = result.Html;

            List<CsharpHttpHelper.Item.ImgItem> imglist = HttpHelper.GetImgList(html);
            return imglist;

        }
        public static string postToPing(string url)
        {
            string re = "";
            try
            {
                string posturl = "http://ping.baidu.com/ping/RPC2"; //post 提交地址
                string refurl = ""; //这里可以随便填写.
                string content_type = "text/xml";        //提交类型.这里一定要text/xml
                string postdt = postdata(url);              //提交数据
                string str = baiduping(posturl, postdt, content_type, refurl, false, Encoding.UTF8);
                Stream sm = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(str)); //下面这里检测提交是否成功
                XmlDocument doc = new XmlDocument();
                doc.Load(sm);
                XmlElement xle = doc.DocumentElement;
                XmlNode node = doc.SelectSingleNode("int");
                string value = node.InnerText;

                if (value != "0")
                {

                    re = "失败";
                }
                else
                {
                    re = "成功";
                }
            }
            catch (Exception ex)
            {
                re = ex.Message;
            }
            return re;
        }
        private static string postdata(string url)
        {
            //注意xml拼接的时候,xml的第一行的开头必须不能有空格等 //下面直接是引用百度的例子
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall>");
            sb.AppendLine(" <methodName>weblogUpdates.extendedPing</methodName>");
            sb.AppendLine("<params>");
            sb.AppendLine(" <param> ");
            sb.AppendLine("<value><string>" + url + "</string></value>");
            sb.AppendLine(" </param> ");
            sb.AppendLine(" <param>");
            sb.AppendLine("<value><string>" + url + "/</string></value>");
            sb.AppendLine("</param>");
            sb.AppendLine(" <param> ");
            sb.AppendLine("<value><string>" + url + "</string></value>");
            sb.AppendLine(" </param> ");
            sb.AppendLine(" <param>");
            sb.AppendLine("<value><string>" + url + "/</string></value>");
            sb.AppendLine("</param>");
            sb.AppendLine("</params>");
            sb.AppendLine("</methodCall>");
            return sb.ToString().Trim();
        }

        private static string baiduping(string targetURL, string formData, string contentType, string referer, bool allowAutoRedirect, Encoding ed)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(formData);
            //请求目标网页
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //使用post方式发送数据
            request.UserAgent = "request";
            request.Referer = referer;
            request.ProtocolVersion = new Version("1.0");  //注意这里这个版本好.一定要设置.现在默认提交是1.1了.否则会一直提示504
            request.ContentType = contentType == "" ? "application/x-www-form-urlencoded" : contentType;
            request.Timeout = 1000 * 10;
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            string html = new StreamReader(stream, ed).ReadToEnd();
            return html;
        }
        public static Image getCodeimage(string url)
        {
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "get",//URL     可选项 默认为Get   
                ResultType = ResultType.Byte
            };
            HttpResult result = http.GetHtml(item);
            cookie = result.Cookie;
            cccookie = result.CookieCollection;
            Image img = HttpHelper.GetImage(result.ResultByte);
            return img;
        }
        public static Loginstatus Login(string name, string pwd, string code)
        {
            HttpItem item1 = new HttpItem()
           {
               URL = "http://b2b.sg560.com/login.aspx",//?vid=7L9Vf4jy5Ih/SFD37L7ZRIeLboNMWN%2BgpYS2U/n0KHgTgknZeTOLMNCgMUhdgaVg",//URL     必需项    
               Method = "get",//URL     可选项 默认为Get 
               Cookie = cookie,
           };
            HttpResult result1 = http.GetHtml(item1);
            //获取请请求的Html
            string html1 = result1.Html;
            string vid = HttpHelper.GetBetweenHtml(html1, "action=\"", "\"");
            HttpItem item = new HttpItem()
            {
                URL = "http://b2b.sg560.com" + vid,//URL     必需项    
                Method = "post",//URL     可选项 默认为Get 
                UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
                ContentType = "application/x-www-form-urlencoded",//返回类型    可选项有默认值
                PostDataType = PostDataType.String,//默认为字符串，同时支持Byte和文件方法
                PostEncoding = System.Text.Encoding.UTF8,//默认为Default，
                Postdata = string.Format("rLogName={0}&rPwd={1}&VAJADATA={2}", name, pwd, code),//Post要发送的数据
                Cookie = cookie,
            };
            //请求的返回值对象
            HttpResult result = http.GetHtml(item);
            //获取请请求的Html
            string html = result.Html;
            //获取请求的Cookie
            //cookie = result.Cookie;
            Loginstatus objjson = (Loginstatus)HttpHelper.JsonToObject<Loginstatus>(html);

            return objjson;
        }
        public static HttpResult PubTitleByte(string url, string post)
        {
            return HttpPostByte(url, post);
        }
        public static HttpResult PubTitle(string url, string post)
        {
            return HttpPost(url, post);
        }
        public static HttpResult PubTitleMulti(string url, string post)
        {
            return HttpPostMulti(url, post);
        }
        public static string Refreshtitle()
        {
            string re = "";
            HttpResult r=HttpGet("http://b2b.sg560.com/handler/UpdateTime.ashx?id=" + myhttp.myid + "&type=1","");
            string data = r.Html;
            if (data == "1" )
            {
                re="刷新完成";
            }
            else if (data == "2")
            {
                re="您今天已经刷新过了，请勿重复刷新";
            }
            else if (data == "3")
            {
                re="您在8小时内已经刷新过了，请勿重复刷新";
            }
            else if (data == "4")
            {
                re="您在6小时内已经刷新过了，请勿重复刷新";
            }
            else if (data == "5")
            {
                re="您在4小时内已经刷新过了，请勿重复刷新";
            }
            else
            {
                re="您这个月已经刷新过了，请勿重复刷新";
            }
            return re;

        }
        public static HttpResult HttpGet(string url, string postDataStr)
        {
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "get",//URL     可选项 默认为Get  
                Cookie = cookie,
            };
            HttpResult result = http.GetHtml(item);

            return result;
        }
        public static List<DropDL> GetDDL(string url, string postDataStr)
        {
            //List<DropDL> list = new List<DropDL>();
            HttpResult result = HttpGet(url, postDataStr);
            //获取请请求的Html
            string html = result.Html;
            //获取请求的Cookie
            //cookie = result.Cookie;
            List<DropDL> list = (List<DropDL>)HttpHelper.JsonToObject<List<DropDL>>(html);
            return list;

        }
        public static string HttpPostmy(string url, string postData)
        {
            HttpWebResponse response;
            HttpWebRequest request;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version10;
            request.UserAgent = "Mozilla/4.0";
            request.Headers.Add("Cookie", cookie);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            Stream stream = request.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            string html = string.Empty;
            try
            {
                //获取服务器返回的资源  
                response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                html = reader.ReadToEnd();
                reader.Close();
                response.Close();                
            }
            catch (Exception ex)
            {
                html = ex.Message;
            }
            return html;
        }
        public static HttpResult HttpPostByte(string url, string postDataStr)
        {
            byte[] bytedate = System.Text.Encoding.UTF8.GetBytes(postDataStr);
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "post",//URL     可选项 默认为Get  
                Cookie = cookie,
                //CookieCollection=cccookie,
                PostdataByte = bytedate,
                PostDataType = PostDataType.Byte,
                Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                ContentType = "application/x-www-form-urlencoded",
                UserAgent ="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",// "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
                PostEncoding = System.Text.Encoding.UTF8,
                //Referer="http://b2b.sg560.com/member/sell/SellTosr" + myhttp.sgid + ".html",
            };
            HttpResult result = http.GetHtml(item);
            return result;
        }
        public static HttpResult HttpPost(string url, string postDataStr)
        {
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "post",//URL     可选项 默认为Get  
                Cookie = cookie,
                Postdata = postDataStr,
                ContentType = "application/x-www-form-urlencoded",
                UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
                PostDataType = PostDataType.String,
                PostEncoding = System.Text.Encoding.UTF8,
            };
            HttpResult result = http.GetHtml(item);
            return result;
        }
        public static string PostWebRequest(string postUrl, string paramData)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                //webReq.CookieContainer=new CookieContainer(
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ret;
        }
        public static HttpResult HttpPostDefault(string url, string postDataStr)
        {
            //byte[] bytedate = System.Text.Encoding.UTF8.GetBytes(postDataStr);
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "post",//URL     可选项 默认为Get  
                //Cookie = cookie,
                //CookieCollection=cccookie,
                //PostdataByte = bytedate,
                Postdata=postDataStr,
                PostDataType = PostDataType.String,
                Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                ContentType = "application/x-www-form-urlencoded",
                UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",// "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
                PostEncoding = System.Text.Encoding.UTF8,
                //Referer="http://b2b.sg560.com/member/sell/SellTosr" + myhttp.sgid + ".html",
            };
            HttpResult result = http.GetHtml(item);
            return result;
        }
        public static HttpResult HttpPostMulti(string url, string postDataStr)
        {
            string boundary = "----WebKitFormBoundaryYajflqIp8XWL7Dxd";
            string[] posts = postDataStr.Split('&');
            string name = "", value = "";
            StringBuilder sb = new StringBuilder();
            foreach (string s in posts)
            {
                name = s.Substring(0, s.IndexOf("="));
                value = s.Substring(s.IndexOf("="));
                byte[] bytedate = System.Text.Encoding.UTF8.GetBytes(value);
                sb.Append("--");
                sb.Append(boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
                sb.Append(bytedate);
                sb.Append("\r\n");
            }
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项    
                Method = "post",//URL     可选项 默认为Get  
                Cookie = cookie,
                Postdata = postDataStr,
                ContentType = "multipart/form-data; boundary=" + boundary,
                UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
                PostEncoding = System.Text.Encoding.UTF8,
            };
            HttpResult result = http.GetHtml(item);
            return result;
        }
        public static string GetValue(string url, string tag, string id)
        {
            string v = "";
            HttpResult r = HttpGet(url, "");
            v = GetHtmlID(r.Html.ToString(), tag, id);
            return v;

        }
        public static List<Category> LoadCategory(string url)
        {
            List<Category> list = new List<Category>();            
            getStrjs(); 
            string main1 = HttpHelper.JavaScriptEval(strjs, "getdsy(0)");
            if (main1.Length > 0)
            {
                main1 = main1.Substring(0, main1.Length - 1);
                string[] cs = main1.Split(',');
                foreach (string s in cs)
                {
                    Category item = new Category
                        {
                            Id = s.Split('|')[0],
                            Name = s.Split('|')[1]
                        };

                    list.Add(item);
                }
            }
            return list;
        }

        public static void getStrjs()
        {
            string url = "http://b2b.sg560.com/SgStyle/js/jsSort.js";
            strjs = string.Empty;
            strjs = HttpGet(url, "").Html.ToString();
            strjs += "function getdsy(i){var s='';var ar=dsy.Items[i];for (var i = 0; i < ar.length; i++) {s+= ar[i]+','; }return s;}";

        }

        public static List<Category> LoadChildren(string id)
        {
            List<Category> list = new List<Category>();
            if (strjs != null && strjs != "")
            {
                try
                {
                    string main1 = HttpHelper.JavaScriptEval(strjs, "getdsy('" + id + "')");
                    if (main1.Length > 0)
                    {
                        main1 = main1.Substring(0, main1.Length - 1);
                        string[] cs = main1.Split(',');
                        foreach (string s in cs)
                        {
                            Category item = new Category
                            {
                                Id = s.Split('|')[0],
                                Name = s.Split('|')[1]
                            };

                            list.Add(item);
                        }
                    }
                }
                catch (Exception)
                {                    
                   
                }
                
            }
            return list;
        }
        public static string GetHtmlID(string html, string tag, string searchid)
        {
            string v = "";
            Regex re = new Regex(@"(<" + tag + @"[\w\W].+?>)");
            MatchCollection imgreg = re.Matches(html);
            List<string> m_Attributes = new List<string>();
            Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);
            Regex id = new Regex(" id=\"(?<value>.*?)\"", RegexOptions.IgnoreCase);
            Regex value = new Regex(" value=\"(?<value>.*?)\"", RegexOptions.IgnoreCase);
            for (int i = 0; i < imgreg.Count; i++)
            {
                MatchCollection matchs = id.Matches(imgreg[i].ToString());
                for (int j = 0; j < matchs.Count; j++)
                {
                    GroupCollection groups = matchs[j].Groups;
                    if (searchid.ToUpper() == groups["value"].Value.ToUpper())
                    {
                        matchs = value.Matches(imgreg[i].ToString());
                        for (int m = 0; m < matchs.Count; m++)
                        {
                            v = matchs[m].Groups["value"].Value.ToString();
                            break;
                        }
                    }
                }
            }
            return v;
        }
        public static string GetHtmlahref(string html, string content)
        {
            string v = "";
            Regex reg = new Regex(@"(?is)<a(?:(?!href=).)*href=(['""]?)(?<url>[^""\s>]*)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
            MatchCollection mc = reg.Matches(html);
            foreach (Match m in mc)
            {
                if (m.Groups["text"].Value.Trim() == content.Trim())
                {
                    v = m.Groups["url"].Value;
                    return v;
                }
            }        
            return v;

        }
        public static string GetHtmlahrefLike(string html, string content)
        {
            string v = "";
            Regex reg = new Regex(@"(?is)<a(?:(?!href=).)*href=(['""]?)(?<url>[^""\s>]*)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
            MatchCollection mc = reg.Matches(html);
            foreach (Match m in mc)
            {
                if (m.Groups["url"].Value.Trim().Contains(content))
                {
                    v = m.Groups["url"].Value;
                    return v;
                }
            }
            return v;

        }
        public static string GetHtmlValue(string html, string tag, string search, string searchattr, string getattr)
        {
            string v = "";
            Regex re = new Regex(@"(<" + tag + @"[\w\W].+?>)");
            MatchCollection imgreg = re.Matches(html);
            List<string> m_Attributes = new List<string>();
            Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);
            Regex id = new Regex(" " + searchattr + "=\"(?<value>.*?)\"", RegexOptions.IgnoreCase);
            Regex value = new Regex(" " + getattr + "=\"(?<value>.*?)\"", RegexOptions.IgnoreCase);
            for (int i = 0; i < imgreg.Count; i++)
            {
                MatchCollection matchs = id.Matches(imgreg[i].ToString());
                for (int j = 0; j < matchs.Count; j++)
                {
                    GroupCollection groups = matchs[j].Groups;
                    if (search.ToUpper() == groups["value"].Value.ToUpper())
                    {
                        matchs = value.Matches(imgreg[i].ToString());
                        for (int m = 0; m < matchs.Count; m++)
                        {
                            v = matchs[m].Groups["value"].Value.ToString();
                            break;
                        }
                    }
                }
            }
            return v;
        }
        private List<string> GetHtmlAttr(string html, string tag, string attr)
        {
            Regex re = new Regex(@"(<" + tag + @"[\w\W].+?>)");
            MatchCollection imgreg = re.Matches(html);
            List<string> m_Attributes = new List<string>();
            Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);
            for (int i = 0; i < imgreg.Count; i++)
            {
                MatchCollection matchs = attrReg.Matches(imgreg[i].ToString());
                for (int j = 0; j < matchs.Count; j++)
                {
                    GroupCollection groups = matchs[j].Groups;
                    if (attr.ToUpper() == groups[1].Value.ToUpper())
                    {
                        m_Attributes.Add(groups[3].Value);
                        break;
                    }
                }
            }
            return m_Attributes;
        }
        public static string getmyid(string url)
        {
            string myid = "";
            string temp = url.Substring(url.IndexOf("index") + 5);
            string mydate = DateTime.Now.ToString("MMddyyyy");
            myid = temp.Substring(0, temp.IndexOf(mydate) - 1);
            return myid;

        }
        public static string getmysgid(string url,string endstr)
        {
            string myid = "";
            string temp = url.Substring(url.IndexOf(endstr) + endstr.Length);
            myid = temp.Substring(0, temp.IndexOf("."));
            return myid;

        }
        public static upimgstatus Upload(string files)
        {
            FileInfo f = new FileInfo(files);
            HttpResult r = HttpGet("http://b2b.sg560.com/member/sell/SellTosr" + myhttp.sgid + ".html", "");
            uploadset = HttpHelper.GetBetweenHtml(r.Html, "handler", "id");
            //"|css|l3Vp0nmYXWPysNRU5hkwJPibEawHdXjE82lDUPTGQMg=|lb|sell|type||F535D1F8504643408964B225|"
            string[] ups = uploadset.Split('|');
            string url = "http://b2b.sg560.com//handler/upload_json.ashx?type=" + ups[7] + "&&id=" + ups[2] + "&&lb=sell";
            byte[] UploadBuffers = null;
            string BoundStr = "-----------------------------7e03473650a70";//根据抓包生成
            StringBuilder UploadBuf = new StringBuilder();
            string ext = f.Extension;

            #region 头部数据
            UploadBuf.Append(BoundStr + "\r\n");
            UploadBuf.Append("Content-Disposition: form-data; name=\"imgFile\"; filename=\"" + DateTime.Now.Ticks+"." +ext+ "\"\r\n");
            UploadBuf.Append("Content-Type: image/jpeg\r\n\r\n");
            //UploadBuf.Append("ÿØÿà\r\n");
            byte[] HeadBytes = Encoding.ASCII.GetBytes(UploadBuf.ToString());
            #endregion

            #region 图片数据
            byte[] PicBytes = ImageToBytesFromFilePath(files);
            #endregion

            #region 尾部数据
            UploadBuf.Remove(0, UploadBuf.Length); ;
            UploadBuf.Append("\r\n" + BoundStr + "\r\n");
            UploadBuf.Append(@"Content-Disposition: form-data; name=""id""" + "\r\n\r\n\r\n");
            UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""proxyurl""" + "\r\n\r\n\r\n");
            UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""jsmode""" + "\r\n\r\ntrue\r\n");
            UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""rule""" + "\r\n\r\nproductImageRule\r\n");
            UploadBuf.Append(BoundStr + "--");
            byte[] TailBytes = Encoding.ASCII.GetBytes(UploadBuf.ToString());
            #endregion

            #region 数组拼接
            UploadBuffers = ComposeArrays(HeadBytes, PicBytes);
            UploadBuffers = ComposeArrays(UploadBuffers, TailBytes);
            #endregion

            #region 上传
            HttpItem item = new HttpItem()
            {
                URL = url,
                Method = "POST",
                ContentType = "multipart/form-data; boundary=" + BoundStr.Substring(2),
                Referer = "http://b2b.sg560.com/member/sell/SellTosr" + myhttp.sgid + ".html",
                PostDataType = PostDataType.Byte,
                PostEncoding = Encoding.UTF8,
                PostdataByte = UploadBuffers,
                Cookie = cookie
            };
            r = http.GetHtml(item);

            #endregion
            upimgstatus objjson = (upimgstatus)HttpHelper.JsonToObject<upimgstatus>(r.Html);

            return objjson;
        }

        public static string ByteToHexString(byte[] bytes)
        {
            string str = string.Empty; if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++) { str += bytes[i].ToString("X2"); }
            }
            return str;
        }

        #region 数组组合
        public static byte[] ComposeArrays(byte[] Array1, byte[] Array2)
        {
            byte[] Temp = new byte[Array1.Length + Array2.Length];
            Array1.CopyTo(Temp, 0);
            Array2.CopyTo(Temp, Array1.Length);
            return Temp;
        }
        #endregion

        #region 图片转Byte数组
        public static byte[] ImageToBytesFromFilePath(string FilePath)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Image Img = Image.FromFile(FilePath))
                {
                    using (Bitmap Bmp = new Bitmap(Img))
                    {
                        Bmp.Save(ms, Img.RawFormat);
                    }
                }
                return ms.ToArray();
            }
        }
        #endregion


        public static string HttpUploadFile(string url, NameValueCollection nvc)
        {
            string r = "";
            var boundary = "---------------------------7e01ff335133c";
            var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Headers.Add("Cookie", cookie);

            var rs = wr.GetRequestStream();

            const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                var formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            var header = string.Format(headerTemplate, "sFileUpload", "", "application/octet-stream");
            var headerbytes = Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            //var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            //var buffer = new byte[4096];
            //var bytesRead = 0;
            //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            //{
            //    rs.Write(buffer, 0, bytesRead);
            //}
            //fileStream.Close();

            var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                var stream2 = wresp.GetResponseStream();
                var reader2 = new StreamReader(stream2);
                r=reader2.ReadToEnd();
                //MessageBox.Show(string.Format("Response is: {0}", reader2.ReadToEnd()));
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error uploading file" + ex);
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
                
            }
            return r;
        }

        //public static byte[] BuildMultipartPostData(string Boundary, Dictionary<string, string> HttpPostData, UploadFile FileUploadData)
        //{
        //    StringBuilder sb = new StringBuilder();

        //    // append access token. 
        //    sb.AppendLine("--" + Boundary);
        //    sb.Append(Environment.NewLine);

        //    // append form part. 
        //    if (HttpPostData != null && HttpPostData.Count > 0)
        //    {
        //        foreach (KeyValuePair<string, string> HttpPostDataItem in HttpPostData)
        //        {
        //            sb.AppendLine("--" + Boundary);
        //            sb.AppendLine(string.Format("Content-Disposition: form-data;name=\"{0}\"", HttpPostDataItem.Key));
        //            sb.Append(Environment.NewLine);
        //            sb.AppendLine(HttpPostDataItem.Value);
        //        }
        //    }

        //    // handle file upload. 
        //    if (FileUploadData != null)
        //    {
        //        sb.AppendLine("--" + Boundary);
        //        sb.AppendLine(string.Format("Content-Disposition: form-data;name=\"{0}\"; filename=\"{1}\"", FileUploadData.Name, FileUploadData.Filename));
        //        sb.AppendLine(string.Format("Content-Type: {0}", FileUploadData.ContentType));
        //        sb.Append(Environment.NewLine);
        //    }

        //    MemoryStream ms = new MemoryStream();
        //    BinaryWriter bw = new BinaryWriter(ms);
        //    bw.Write(Encoding.Default.GetBytes(sb.ToString()));
        //    bw.Write(FileUploadData.Data);
        //    bw.Write(Encoding.Default.GetBytes(Environment.NewLine));
        //    bw.Write(Encoding.Default.GetBytes("--" + Boundary));
        //    ms.Flush();
        //    ms.Position = 0;

        //    byte[] result = ms.ToArray();

        //    bw.Close();

        //    return result;
        //}


        //public static string MakeHttpPost(string RequestUrl, Dictionary<string, string> HttpPostData, UploadFile FileUploadData)
        //{
        //    HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest;
        //    HttpWebResponse response = null;

        //    StreamReader sr = null;
        //    string boundary = "---------------------------7e01ff335133c";

        //    try
        //    {
        //        request.Method = "POST";
        //        request.ContentType = "multipart/form-data; boundary=" + boundary;

        //        byte[] multipartPostData = BuildMultipartPostData(boundary, HttpPostData, FileUploadData);

        //        BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
        //        bw.Write(multipartPostData);
        //        bw.Close();

        //        response = request.GetResponse() as HttpWebResponse;

        //        sr = new StreamReader(response.GetResponseStream());
        //        string responseData = sr.ReadToEnd();
        //        sr.Close();

        //        response.Close();

        //        return responseData;
        //    }
        //    catch (WebException we)
        //    {
        //        throw new Exception(we.Message);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }
        //}

        private static readonly Encoding encoding = Encoding.UTF8;
        public static string MultipartFormDataPost(string postUrl, Dictionary<string, object> postParameters)
        {
            string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
            string contentType = "multipart/form-data; boundary=" + formDataBoundary;

            byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);

            HttpWebResponse webResponse = PostForm(postUrl, contentType, formData);

            // Process response
            StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
            string html = responseReader.ReadToEnd();
            webResponse.Close();
            return html;
        }
        private static HttpWebResponse PostForm(string postUrl, string contentType, byte[] formData)
        {
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            // Set up the request properties.
            request.Method = "POST";
            request.ContentType = contentType;
            request.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
            //request.
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586";
            request.CookieContainer = new CookieContainer();
            request.ContentLength = formData.Length;
            request.Headers.Add("Cookie", cookie);
            request.Headers.Add("Accept-Encoding:gzip, deflate");
            request.Headers.Add("Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
                
            // You could add authentication here as well if needed:
            // request.PreAuthenticate = true;
            // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
            // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

            // Send the form data to the request.
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(formData, 0, formData.Length);
                requestStream.Close();
            }

            return request.GetResponse() as HttpWebResponse;
        }

        private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        {
            Stream formDataStream = new System.IO.MemoryStream();
            bool needsCLRF = false;

            foreach (var param in postParameters)
            {
                // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
                // Skip it on the first parameter, add it to subsequent parameters.
                if (needsCLRF)
                    formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));

                needsCLRF = true;

                if (param.Value is FileParameter)
                {
                    FileParameter fileToUpload = (FileParameter)param.Value;

                    // Add just the first part of this param, since we will write the file data directly to the Stream
                    string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                        boundary,
                        param.Key,
                        fileToUpload.FileName ?? param.Key,
                        fileToUpload.ContentType ?? "application/octet-stream");

                    formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

                    // Write the file data directly to the Stream, rather than serializing it to a string.
                    //formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
                }
                else
                {
                    string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                        boundary,
                        param.Key,
                        param.Value);
                    formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
                }
            }

            // Add the end of the request.  Start with a newline
            string footer = "\r\n--" + boundary + "--\r\n";
            formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));

            // Dump the Stream into a byte[]
            formDataStream.Position = 0;
            byte[] formData = new byte[formDataStream.Length];
            formDataStream.Read(formData, 0, formData.Length);
            formDataStream.Close();

            return formData;
        }

        public class FileParameter
        {
            public byte[] File { get; set; }
            public string FileName { get; set; }
            public string ContentType { get; set; }
            public FileParameter(byte[] file) : this(file, null) { }
            public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
            public FileParameter(byte[] file, string filename, string contenttype)
            {
                File = file;
                FileName = filename;
                ContentType = contenttype;
            }
        }

       
        /// <summary>
        /// 上传文件
        /// </summary>
        public class UploadFile
        {
            public UploadFile()
            {
                ContentType = "application/octet-stream";
            }
            public string Name { get; set; }
            public string Filename { get; set; }
            public string ContentType { get; set; }
            public byte[] Data { get; set; }
        }
    }
}
